import pyautogui
import time
import cv2
import numpy as np
from utils import capture_screenshot

base_y = 981

def crop_border(image, border_size=4):
    """
    去掉图片边框
    :param image: 输入图片
    :param border_size: 边框大小
    :return: 去掉边框后的图片
    """
    return image[border_size:-border_size, border_size:-border_size]

def capture_region_and_save_cut(image_path):
    """
    制作牌的模板
    """
    # 读取手牌图片
    hand_image = cv2.imread(image_path, cv2.IMREAD_COLOR)
    hand_width = hand_image.shape[1]

    # 每张牌的宽度
    tile_width = 75

    # 手动调整后的 start_x 数组
    start_x_values = [3, 78, 152, 226, 301, 376, 451, 525, 599, 674, 749, 824, 898]
    if hand_width > 975:
        start_x_values = [3, 78, 152, 226, 301, 376, 451, 525, 599, 674, 749, 824, 898, 996]

    tiles = []
    for i in range(len(start_x_values)):
        start_x = start_x_values[i]
        end_x = start_x + tile_width
        tile = hand_image[:, start_x:end_x]
        tiles.append(tile)

    # 去掉边框并匹配模板
    for i, tile in enumerate(tiles):
        # 去掉边框
        cropped_tile = crop_border(tile)

        # 保存处理后的手牌图片
        save_path = f"images/tem{i + 1}.png"
        cv2.imwrite(save_path, cropped_tile)
        print(f"已保存处理后的第 {i + 1} 张手牌图片: {save_path}")

def capture_region_and_save(region, save_path, scale_factor=2):
    """
    截图手牌区，制作base.png
    """
    try:
        # 等待2秒，确保有足够时间切换到需要截图的窗口
        time.sleep(2)
        # 截取指定区域的图像
        left, top, width, height = region
        new_left = int(left)
        new_top = int(base_y - top)
        new_width = int(width)
        new_height = int(height)
        search_region = (new_left, new_top, new_width, new_height)
        screenshot = pyautogui.screenshot(region=search_region)
        # 保存截图到指定路径
        screenshot.save(save_path)
        print(f"截图已保存到 {save_path}")
    except Exception as e:
        print(f"截图过程中出现错误: {e}")


if __name__ == "__main__":
    # 示例 search_region，需要根据实际情况修改
    regions =[(1036, base_y - 255, 10, 10)]
    time.sleep(2)
    test_save_path = "images/package/hu.png"
    image = pyautogui.screenshot(region=(0,0,1512,982))
    image = np.array(image)
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

    for (x, y, w, h) in regions:
        # 在图片上绘制红色矩形框
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
    cv2.imwrite(test_save_path, image)
#     capture_region_and_save_cut("images/base2.png")
